package com.bieber.smartpost.invoke.filter.filler;

import com.bieber.smartpost.httpcore.Header;
import com.bieber.smartpost.invoke.FilterContext;
import com.jbeer.framework.annotation.Bean;

import java.util.List;
import java.util.regex.Pattern;

/**
 * 从上一个请求返回的header里面取值
 * #{header:'xxxx'[default:xxxx]}
 * Created by bieber on 14-11-30.
 */
@Bean
public class HeaderFiller extends BasicFiller<Header> {

    private static final String EXPRESSION_REGEX="('[\\w-]+')";

    private static final Pattern HEADER_PATTERN = Pattern.compile("#\\{header:"+EXPRESSION_REGEX+DEFAULT_VALUE_REGEX+"\\}");

    @Override
    protected String getExpressionRegex() {
        return EXPRESSION_REGEX;
    }

    protected String convertValue(String originValue,Header header){
        List<FillerRule> ruleList = generateFillerRule(HEADER_PATTERN,originValue);
        if(ruleList.size()<=0){
            return originValue;
        }
        String[] args = new String[ruleList.size()];
        for(int i=0;i<ruleList.size();i++){
            FillerRule rule = ruleList.get(i);
            String value = header.get(rule.getExpression());
            if(value!=null){
                args[i]=value;
            }
        }
        originValue = HEADER_PATTERN.matcher(originValue).replaceAll("%s");
        return String.format(originValue,args);
    }

    @Override
    protected Header generateDataSource(FilterContext context) {
        return context.getLastResponse().getHeader();
    }


    public static void main(String[] args){
        String content = "fdsfasdfsd#{header:'ddadcda'[default:xxxx]}fdfadsf#{header:'xxx'}";
        /*Matcher matcher = HEADER_PATTERN.matcher(content);
        while(matcher.find()){
            System.out.println(matcher.group());
        }*/
        HeaderFiller filler = new HeaderFiller();
        List<FillerRule> ruleList =  filler.generateFillerRule(HEADER_PATTERN,content);
        System.out.println(ruleList);
    }


}
